package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wanghaotian
 * time:2022/12/16,0016 9:02
 * description:
 */

@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {

    @Autowired
    private DtsPermissionMapper permissionMapper;

    @Override
    public Set<String> findPermsByRolesId(Integer[] roleIds) {
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DtsPermission::getRoleId,roleIds);
        wrapper.eq(DtsPermission::getDeleted,false);
        List<DtsPermission> dtsPermissions = permissionMapper.selectList(wrapper);
        Set<String> perms = dtsPermissions.stream().map((perm)->{
            return perm.getPermission();
        }).collect(Collectors.toSet());
        return perms;
    }

    @Override
    public void updatePermissions(Integer roleId, List<String> permissions) {
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId,roleId);
        permissionMapper.delete(wrapper);

        if (permissions != null && permissions.size() > 0) {
            for (String permission : permissions) {
                DtsPermission permission1 = new DtsPermission();
                permission1.setPermission(permission);
                permission1.setRoleId(roleId);
                permission1.setAddTime(new Date());
                permission1.setUpdateTime(new Date());
                permission1.setDeleted(false);
                permissionMapper.insert(permission1);
            }
        }
    }
}
